package cc.angis.xiugallery.account;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import cc.angis.xiugallery.R;
import cc.angis.xiugallery.UserAccountActivity;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.common.NetworkManager;
import cc.angis.xiugallery.data.CommentData;
import cc.angis.xiugallery.data.UserAccount;
import cc.angis.xiugallery.db.CommentDBHelper;
import cc.angis.xiugallery.db.PostDBHelper;
import cc.angis.xiugallery.db.PostPlatformDBHelper;
import cc.angis.xiugallery.db.TableConstants;
import cc.angis.xiugallery.db.UserAccountDBHelper;

import com.tencent.weibo.api.TAPI;
import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

public class QQWeiboAccountManager implements IAccountManager {
	
	private static final String redirectUri = "http://keep.im";
	
	private Context context;
	
	private OAuthV2 oAuth;
	
	public QQWeiboAccountManager(Context context){
		this.context = context;
	}

	@Override
	public void doAuth() {
		oAuth=new OAuthV2(redirectUri);
		oAuth.setClientId(GlobalConst.QQ_CONSUMER_KEY);
		oAuth.setClientSecret(GlobalConst.QQ_CONSUMER_SECRET);
		 Intent intent = new Intent(context,
				 OAuthV2AuthorizeWebView.class);   
				 intent.putExtra("oauth", oAuth);  
		((Activity)context).startActivityForResult(intent, 1);  //请设置合适的requsetCode
	}

	@Override
	public void setContext(Context context) {
		this.context = context;
	}
	
	public void doAuth2(OAuthV2 oAuth){
		this.oAuth = oAuth;
        //调用API获取用户信息
        UserAPI userAPI=new UserAPI(OAuthConstants.OAUTH_VERSION_2_A);
        try {
            String response=userAPI.info(oAuth, "json");//获取用户信息
            UserAccountDBHelper dbHelper  = new UserAccountDBHelper(context, TableConstants.TABLE_USER_ACCOUNT);
			try {
				JSONObject object = new JSONObject(response);
				if (object.getInt("ret") != 0){
					Toast.makeText(context, "获取用户信息失败！", Toast.LENGTH_SHORT).show();
					return;
				}
				String uid = object.getJSONObject("data").getString("openid");
				String username = object.getJSONObject("data").getString("nick");
				String avatar_url = object.getJSONObject("data").getString("head");
				if (!dbHelper.isExist(TableConstants.UserAccount.USER_ID, TableConstants.UserAccount.ACCOUNT_TYPE, uid,  GlobalConst.AccountType.ACCOUNT_TYPE_QQ+"")){
					dbHelper.insert(uid, username, oAuth.getAccessToken()+":::"+oAuth.getOpenid(), Long.parseLong(oAuth.getExpiresIn()), GlobalConst.AccountType.ACCOUNT_TYPE_QQ, avatar_url+"/100");
				} else {
					dbHelper.update(uid, username, oAuth.getAccessToken()+":::"+oAuth.getOpenid(), Long.parseLong(oAuth.getExpiresIn()), GlobalConst.AccountType.ACCOUNT_TYPE_QQ, avatar_url+"/100");
				}
				
			} catch (JSONException e) {
				e.printStackTrace();
			} finally{
				dbHelper.closeDB();
			}
//            ((TextView)findViewById(R.id.textView)).setText(response+"\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        userAPI.shutdownConnection();
        if (context instanceof UserAccountActivity)
        	((UserAccountActivity)context).onCreate(null);
	}

	@Override
	public void sharePic(UserAccount account, String postId, String content,
			String imgPath) {
		oAuth = new OAuthV2();
		oAuth.setAccessToken(account.getAccessToken().split(":::")[0]);
		oAuth.setScope("all");
		oAuth.setOpenid(account.getAccessToken().split(":::")[1]);
		oAuth.setClientId(GlobalConst.QQ_CONSUMER_KEY);
		oAuth.setClientIP(NetworkManager.getLocalIpAddress());
		new ShareWeiboTask().execute(content, imgPath, postId);
		
	}

	@Override
	public void retrieveComments(final UserAccount account, String postId, String platformId) {
		oAuth = new OAuthV2();
		oAuth.setAccessToken(account.getAccessToken().split(":::")[0]);
		oAuth.setScope("all");
		oAuth.setOpenid(account.getAccessToken().split(":::")[1]);
		oAuth.setClientId(GlobalConst.QQ_CONSUMER_KEY);
		oAuth.setClientIP(NetworkManager.getLocalIpAddress());
		new RetrieveCommentsTask().execute(platformId, postId);
	}
	 
	public class ShareWeiboTask extends AsyncTask<String, Void, Integer>{

		@Override
		protected Integer doInBackground(String... params) {
			TAPI tAPI = new TAPI("2.a");
			try {
				String response = tAPI.addPic(oAuth, "json", params[0], NetworkManager.getLocalIpAddress(), params[1]);
				PostPlatformDBHelper dbHelper = new PostPlatformDBHelper(context, TableConstants.TABLE_POST_PLATFORM);
				try{
					JSONObject object = new JSONObject(response);
					if (object.getInt("ret") != 0){
//						Toast.makeText(context, "发表微博至腾讯微博出错！", Toast.LENGTH_SHORT).show();
						return object.getInt("ret");
					}
					String platformId = String.valueOf(object.getJSONObject("data").getString("id"));
					dbHelper.insert(params[2], platformId, GlobalConst.AccountType.ACCOUNT_TYPE_QQ);
				} catch (Exception e){
					e.printStackTrace();
				} finally{
					dbHelper.closeDB();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally{
				tAPI.shutdownConnection();
			}
			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (result == 3){
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setTitle(R.string.dialog_tokenexpired_title).setMessage(R.string.dialog_tokenexpired_text)
				.setPositiveButton(R.string.dialog_authorize, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						doAuth();
					}
				}).setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				}).show();
			}
			super.onPostExecute(result);
		}
		
	}
	
	public class RetrieveCommentsTask extends AsyncTask<String, Void, Integer>{

		@Override
		protected Integer doInBackground(String... params) {
			String lastCommentId = "0";
			String lastCommentTime = "";
			CommentDBHelper dbhelper = new CommentDBHelper(context, TableConstants.TABLE_COMMENT);
			try{
				CommentData lastComment = dbhelper.getLastCommentByType(GlobalConst.AccountType.ACCOUNT_TYPE_QQ);
				if (lastComment !=null && lastComment.getCommentId()!=null)
					lastCommentId = lastComment.getCommentId();
				if (lastComment !=null && lastComment.getTime()!=-1)
					lastCommentTime = lastComment.getTime()/1000 +"";
			} catch(Exception e){
				e.printStackTrace();
			} finally{
				dbhelper.closeDB();
			}
			TAPI tAPI = new TAPI("2.a");
			try {
				String response = tAPI.reList(oAuth, "json", "1", params[0], "0", lastCommentTime, "100", lastCommentId);
				CommentDBHelper dbHelper = new CommentDBHelper(context, TableConstants.TABLE_COMMENT);
				PostDBHelper pDbHelper = new PostDBHelper(context, TableConstants.TABLE_POST);
				try{
					JSONObject object = new JSONObject(response);
					if (object.getInt("ret") != 0){
//						Toast.makeText(context, "发表微博至腾讯微博出错！", Toast.LENGTH_SHORT).show();
						return -1;
					}
					JSONArray comments = object.getJSONObject("data").getJSONArray("info");
					JSONObject comment;
					for (int i=0; i<comments.length(); i++){
						comment = comments.getJSONObject(i);
						if (!dbHelper.isExist(TableConstants.CommentColumn.COMMENT_ID, comment.getString("id")))
							dbHelper.insert(comment.getString("id"), params[1], comment.getString("text"), comment.getString("nick"), comment.getString("head")+"/100", 
									Long.parseLong(comment.getString("timestamp")+"000"), GlobalConst.AccountType.ACCOUNT_TYPE_QQ);
						long postLastUpdate = pDbHelper.getPostLastUpdateByPostId(params[1]);
						if(postLastUpdate < Long.parseLong(comment.getString("timestamp"))*1000){
							pDbHelper.update(params[1], 0, Long.parseLong(comment.getString("timestamp"))*1000);
						}
					}
					
					
				} catch (Exception e){
					e.printStackTrace();
				} finally{
					dbHelper.closeDB();
					pDbHelper.closeDB();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally{
				tAPI.shutdownConnection();
			}
			return 0;
		}
		
	}
	
	@Override
	public void unbind() {
		UserAccountDBHelper dbHelper = new UserAccountDBHelper(context, TableConstants.TABLE_USER_ACCOUNT);
		try{
			dbHelper.deleteByType(GlobalConst.AccountType.ACCOUNT_TYPE_QQ);
		} catch(Exception e){
			e.printStackTrace();
		} finally{
			dbHelper.closeDB();
		}
	}

}
